package cn.gameback.supervisionservices.service.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

// 发送邮件类
@Service
public class SendEmailService {
    @Autowired
    private JavaMailSenderImpl mailSender;

    @Value("${spring.mail.username}")
    private String from;

    // 纯文本的文字发送
    public void sendSimpleMail(String to, String subject, String content) {
        // 定制纯文本邮件信息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            System.out.println("纯文本右键发送成功...");
        } catch(MailException e) {
            System.out.println("纯文本右键发送失败... 失败原因为：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 复杂邮件的发送 包含图片以及附件
    public void sendCompleMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            // 使用MimeMessageHelper 构建 MimeMessage 对象中的内容
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            // 转换附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            // 添加邮件附件
            helper.addAttachment(fileName, file);
            // 发送邮件
            mailSender.send(message);
            System.out.println("复杂邮件发送成功...");
        } catch (MessagingException e) {
            System.out.println("复杂邮件发送失败... 失败原因为：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
